package com.iflytek.crvoice2txt.util;

import android.os.Handler;
import android.widget.ImageView;

import com.iflytek.crvoice2txt.R;

import java.util.Timer;
import java.util.TimerTask;

public class VoicePlayingBgUtil {

    private Handler handler;

    private ImageView imageView;

    private ImageView lastImageView;

    private Timer timer = new Timer();
    private TimerTask timerTask;

    private int i;

    private int[] rightVoiceBg = new int[]{R.drawable.sound1, R.drawable.sound2, R.drawable.sound3};

    public VoicePlayingBgUtil(Handler handler) {
        super();
        this.handler = handler;
    }

    public void voicePlay() {
        if (imageView == null) {
            return;
        }
        i = 0;
        timerTask = new TimerTask() {

            @Override
            public void run() {
                if (imageView != null) {
                    changeBg(rightVoiceBg[i % 3], false);
                } else {
                    return;
                }
                i++;
            }
        };
        timer.schedule(timerTask, 0, 500);
    }

    public void stopPlay() {
        lastImageView = imageView;
        if (lastImageView != null) {
            changeBg(R.drawable.sound3, true);
        }
        if (timerTask != null) {
            timerTask.cancel();
        }
    }


    private void changeBg(final int id, final boolean isStop) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (isStop) {
                    lastImageView.setImageResource(id);
                } else {
                    imageView.setImageResource(id);

                }
            }
        });
    }

    public void setImageView(ImageView imageView) {
        this.imageView = imageView;
    }

}